package cn.edu.njust.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServerHandler extends ChannelInboundHandlerAdapter {

    private static final ChannelGroup group = new DefaultChannelGroup("Client Group", GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        group.writeAndFlush(ctx.channel().remoteAddress() + "上线了");
        group.add(ctx.channel());
        log.info("{}上线了", ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("{}说：{}", ctx.channel().remoteAddress(), msg);
        group.writeAndFlush(msg, new ChannelMatcher() {
            @Override
            public boolean matches(Channel channel) {
                return channel != ctx.channel();
            }
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        group.remove(ctx.channel());
        group.writeAndFlush(ctx.channel().remoteAddress() + "下线了");
        log.info("{}下线了", ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
